package business

import (
	"fmt"
	"strings"
	"time"

	"example.com/m/util"
	"github.com/pkg/errors"
)

type IPInfoController interface {
	GetIPInfo(ip string) (string, error)
}

type WhoIsIPInfoController struct{}

func (c *WhoIsIPInfoController) GetIPInfo(ip string) (string, error) {
	url := fmt.Sprintf("https://whois.pconline.com.cn/jsLabel.jsp?ip=%s&id=showIpInfo", ip)
	v, err := util.HttpGet(url, nil, 5*time.Second)
	if err != nil {
		return "", errors.Wrap(err, "http get timeout")
	}

	respTmp := util.ConvertToString(v, "gbk", "utf-8")
	// document.getElementById('showIpInfo').innerHTML=' 美国CloudFlare公司CDN节点';
	var ipInfo string
	if strings.Contains(respTmp, "=") {
		tmp := strings.Trim(strings.Split(respTmp, "=")[1], ";")
		tmp = strings.Trim(tmp, "\n")
		tmp = strings.Trim(tmp, ";")
		tmp = strings.Trim(tmp, "'")
		ipInfo = strings.Trim(tmp, " ")
	}

	return ipInfo, nil
}

func getLocationInfo(ip string) (string, error) {
	url := fmt.Sprintf("https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?resource_id=6006&format=json&tn=baidu&query=%s", ip)
	v, err := util.HttpGet(url, nil, 5*time.Second)
	if err != nil {
		return "", errors.Wrap(err, "http get timeout")
	}

	respTmp := util.ConvertToString(v, "gbk", "utf-8")
	c1 := strings.Split(respTmp, "location\":\"")[1]
	location := strings.Split(c1, "\",\"")[0]

	return location, nil
}

var (
	defaultWhoIsIPInfoController = &WhoIsIPInfoController{}
)

func newIPInfoController(mode string) (IPInfoController, error) {
	switch mode {
	case string(WhoIsIPInfoMode):
		return defaultWhoIsIPInfoController, nil
	}

	return nil, errors.Errorf("invalid IPInfoController: %v", mode)
}
